package net.zio.kamenriderzioaddon.network.message;

import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.network.NetworkEvent;
import net.zio.kamenriderzioaddon.network.IMessage;
import net.zio.kamenriderzioaddon.ridersystem.data.PlayerDataManager;

import java.util.UUID;
import java.util.function.Supplier;

/**
 * 数据同步数据包
 *
 * @author QianYunYi
 */
public final class SyncPlayerDataPacket implements IMessage {

    private final CompoundTag nbt;
    private final UUID target;

    /* ── 服务端 → 客户端专用：target 为接收者 ── */
    public SyncPlayerDataPacket(CompoundTag nbt, UUID target) {
        this.nbt   = nbt;
        this.target = target == null ? Util.NIL_UUID : target;
    }

    /* ── 解码 ── */
    public SyncPlayerDataPacket(FriendlyByteBuf buf) {
        this.nbt   = buf.readNbt();
        this.target = buf.readUUID();
    }

    /* ── 编码 ── */
    @Override
    public void encode(FriendlyByteBuf buf) {
        buf.writeNbt(nbt);
        buf.writeUUID(target);
    }

    /* ── 处理 ── */
    @Override
    public void handle(NetworkEvent.Context ctx) {
        if (ctx.getDirection().getReceptionSide().isClient()) {
            ctx.enqueueWork(() -> {
                Player clientPlayer = Minecraft.getInstance().player;
                if (clientPlayer != null &&
                        (target.equals(Util.NIL_UUID) || clientPlayer.getUUID().equals(target))) {
                    PlayerDataManager.get(clientPlayer).deserializeNBT(nbt);
                }
            });
        }
        ctx.setPacketHandled(true);
    }
}